<template>
    <div class="role-popup">
        <el-dialog
            :before-close="_close"
            :visible.sync="propValue"
            title="权限配置"
            width="50%"
            top="5vh"
        >
            <div style="max-height:70vh;overflow-x: hidden">
                <el-tabs class="tabs" v-model="activeName" stretch type="border-card" @tab-click="handleClick">
                    <el-tab-pane label="菜单权限" name="1">
                        <el-tree
                            ref="menu"
                            empty-text="暂无配置"
                            default-expand-all
                            :data="menuData"
                            :default-checked-keys="menuPermissions"
                            node-key="value"
                            show-checkbox
                        ></el-tree>
                    </el-tab-pane>
                    <el-tab-pane label="接口权限" name="2">
                        <el-tree
                            ref="apiScope"
                            :data="apiScopeData"
                            empty-text="暂无配置"
                            default-expand-all
                            :default-checked-keys="apiScopePermissions"
                            node-key="value"
                            show-checkbox
                        ></el-tree>
                    </el-tab-pane>
                </el-tabs>
                <div slot="footer" class="btn-box">
         <span class="dialog-footer">
            <el-button size="medium" type="primary" @click="onSubmit">保存</el-button>
            <el-button size="medium" @click="_close">取消</el-button>
        </span>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>

export default {
    name: 'rolePopup',
    components: {},
    props: {
        value: {
            type: Boolean,
            default: false,
        },
        currentData: {
            type: Object,
            default() {
                return {}
            },
        },
    },
    data() {
        return {
            activeName: '1',
            menuData: [],
            menuPermissions: [],
            apiScopeData: [],
            apiScopePermissions: [],
            checkStrictly: true,
        }
    },
    computed: {
        propValue: {
            get() {
                this.activeName = '1'
                return this.value
            },
            set(nval) {
                this.$emit('input', nval)
            },
        },
    },
    methods: {
        async findAllTree() {
            let {code, data} = await this.$api.menu.findAllTree()
            if (code === 200) {
                await this.getRolePermissions(data)
            }
        },

        async getRolePermissions(treeData) {
            let params = {
                roleId: this.currentData.id,
            }
            let {code, data} = await this.$api.permission.roleMenu.getMenuByRoleId(params)
            if (code === 200) {
                this.menuPermissions = data.filter(v => !v.hasChildren).map(v => {
                    return v.menuId
                })
                this.menuData = treeData
            }
        },
        /**
         * 处理菜单数组：apiUrl不为空的节点设为disabled: false，其余设为disabled: true
         * @param {Array} originalMenuData - 原始菜单数据数组（即JSON中的data字段）
         * @returns {Array} 处理后的全新菜单数组（不修改原数据）
         */
        processMenuDisabled(originalMenuData) {
            // 1. 深拷贝原始数据，避免修改原数组（关键：确保返回新数组而非修改原数据）
            const newMenuData = JSON.parse(JSON.stringify(originalMenuData));

            // 2. 递归处理所有层级节点的disabled属性
            function setDisabled(nodeList) {
                nodeList.forEach(node => {
                    // 判断apiUrl是否有效：存在 + 非null/undefined + 非空字符串
                    const isApiUrlValid =
                        node.hasOwnProperty('apiUrl') &&
                        node.apiUrl !== null &&
                        node.apiUrl !== undefined &&
                        node.apiUrl.trim() !== '';

                    // 给当前节点添加disabled属性
                    node.disabled = !isApiUrlValid;

                    // 递归处理子节点（若存在有效children数组）
                    if (node.children && Array.isArray(node.children) && node.children.length > 0) {
                        setDisabled(node.children);
                    }
                });
            }

            // 3. 执行处理逻辑
            setDisabled(newMenuData);

            // 4. 返回处理后的全新数组
            return newMenuData;
        },
        async findApiByMenuTree() {
            let {code, data} = await this.$api.permission.apiScope.findApiByMenuTree()
            if (code === 200) {
                await this.getApiIdByRoleId(this.processMenuDisabled(data))
            }
        },

        async getApiIdByRoleId(treeData) {
            let params = {
                roleId: this.currentData.id,
            }
            let {code, data} = await this.$api.permission.roleApi.getApiIdByRoleId(params)
            if (code === 200) {
                this.apiScopePermissions = data
                this.apiScopeData = treeData
            }
        },

        handleClick(tab, event) {
            +this.activeName === 1 ? this.findAllTree() : this.findApiByMenuTree()
        },

        onSubmit() {
            // console.log('选中的包含父级keys', this.$refs.menu.getCheckedKeys())
            // console.log('选中的不包含父级keys', this.$refs.menu.getCheckedKeys(true))
            // console.log('全部选中包含半选', this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys()))

            +this.activeName === 1 ? this.roleAddMenu() : this.roleAddApi()
        },
        async roleAddMenu() {
            let params = {
                roleId: this.currentData.id,
                menuIds: this.$refs.menu.getCheckedKeys(false)
            }

            let {code, msg} = await this.$api.permission.roleMenu.roleAddMenu(params)

            if (code === 200) {
                this.$message.success('配置成功' || msg)
                this.$emit('input', false)
            }
        },

        async roleAddApi() {
            let params = {
                roleId: this.currentData.id,
                apiIds: this.$refs.apiScope.getCheckedKeys(true)
            }

            let {code, msg} = await this.$api.permission.roleApi.roleAddApi(params)

            if (code === 200) {
                this.$message.success('配置成功' || msg)
                this.$emit('input', false)
            }
        },

        //关闭弹窗
        _close() {
            this.menuData = []
            this.permissions = []
            this.$emit('input', false)
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep.role-popup {
    .el-tabs {
        position: relative;
        max-height: 70vh;
        overflow-y: scroll;
    }

    .btn-box {
        position: absolute;
        bottom: 30px;
        right: 40px;
        z-index: 999999;

        .dialog-footer {

            .el-button {
                margin-top: 20px !important;
            }

        }
    }


}

</style>
